const json = [
  {
    id: 1,
    name: "1",
    parentId: 0,
  },
  {
    id: 3,
    name: "3",
    parentId: 0,
  },
  {
    id: 11,
    name: "11",
    parentId: 1,
  },
  {
    id: 12,
    name: "12",
    parentId: 1,
  },
  {
    id: 13,
    name: "13",
    parentId: 1,
  },
  {
    id: 111,
    name: "111",
    parentId: 11,
  },
  {
    id: 112,
    name: "112",
    parentId: 2,
  },
  {
    id: 21,
    name: "21",
    parentId: 2,
  },
  {
    id: 211,
    name: "211",
    parentId: 21,
  },
  {
    id: 1111,
    name: "1111",
    parentId: 111,
  },
  {
    id: 2,
    name: "2",
    parentId: 0,
  },
];

// json -> tree JSON扁平数据转换为Tree形数据
const jsonToTree = (jsonData, option) => {
  const _defaultOption = {
    id: "id",
    pid: "pid",
    children: "children",
    rid: 0,
  };

  const { id, pid, children, rid } = Object.assign({}, _defaultOption, option);

  const map = {};
  const tree = [];
  jsonData.reduce((map, item) => {
    map[item[id]] = item;
    if (item[pid] === rid) {
      tree.push(item);
    }
    return map;
  }, map);
  json.forEach((item) => {
    if (map[item[pid]]) {
      (map[item[pid]][children] || (map[item[pid]][children] = [])).push(item);
    }
  });
  return tree;
};
const treeData = jsonToTree(json, {
  id: "id",
  pid: "parentId",
  children: "children",
});
// console.log('tree', JSON.stringify(treeData, null, 2))

// tree -> json 树结构转换为JSON扁平数据
const treeToJson = (tree, option) => {
  const _defaultOption = {
    pid: "pid",
    children: "children",
  };

  const { children } = Object.assign(_defaultOption, option);

  const json = [];
  const map = (data) => {
    const queue = [];
    data.forEach((item) => {
      queue.push(item);
    });
    while (queue.length) {
      const item = queue.shift();
      const children = item.children;
      item.children = null;
      delete item.children;
      json.push({
        ...item,
      });
      if (children) {
        children.forEach((child) => queue.push(child));
      }
    }
  };
  map(tree);
  console.log("json", json);
};
treeToJson(treeData, {
  pid: "parent",
  children: "kids",
});
